package com.hgy.crowd.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.PutObjectResult;
import com.hgy.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author He
 * @Date 2020/3/30 17:20
 * @Version 1.0
 * 判断当前请求是否为Ajax请求
 * 密码加密
 */

public class CrowdUtil {
    /**
     *  发送短信服务
     * @param host  短信接口请求地址
     * @param path  请求的具体url
     * @param appcode   服务的appcode码
     * @param sign  签名编号
     * @param skin  模板编号
     * @param phone 要发送的手机号
     * @return
     */
    public static ResultEntity sendMessage(String host,String path,String appcode,String sign,String skin,String phone){
        StringBuilder stringBuilder= new StringBuilder(6);
        for (int i=1;i<=6;i++){
            double random = Math.random()*10;
            stringBuilder.append((int) random);
        }
        String param = stringBuilder.toString();
        String urlSend = host + path + "?sign=" + sign + "&skin=" + skin+ "&param=" + param+ "&phone=" + phone;
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 格式Authorization:APPCODE
            httpURLConnection.setRequestProperty("Authorization", "APPCODE " + appcode);
            // (中间是英文空格)
            int httpCode = httpURLConnection.getResponseCode();
            if (httpCode == 200) {
                //正常发出短信
                return ResultEntity.successWithData(param);
            } else {
                Map<String, List<String>> map = httpURLConnection.getHeaderFields();
                String errorMessage = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && errorMessage.equals("Invalid AppCode `not exists`")) {
                    //AppCode错误
                    return ResultEntity.failed("系统内部错误");
                } else if (httpCode == 400 && errorMessage.equals("Invalid Url")) {
                    //请求的 Method、Path 或者环境错误
                    return ResultEntity.failed("系统内部错误");
                } else if (httpCode == 400 && errorMessage.equals("Invalid Param Location")) {
                    //参数错误
                    return ResultEntity.failed("系统内部错误");
                } else if (httpCode == 403 && errorMessage.equals("Unauthorized")) {
                    //服务未被授权（或URL和Path不正确）
                    return ResultEntity.failed("系统内部错误");
                } else if (httpCode == 403 && errorMessage.equals("Quota Exhausted")) {
                    //套餐包次数用完
                    return ResultEntity.failed("系统内部错误");
                } else if(httpCode == 101){
                    return ResultEntity.failed("手机号码填写错误");
                } else if (httpCode==102){
                    return ResultEntity.failed("参数不能为空");
                }else {
                    return ResultEntity.failed("其他错误");
                }
            }

        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
            return ResultEntity.failed("系统内部错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
            return ResultEntity.failed("系统内部错误");
        } catch (Exception e) {
            // 打开注释查看详细报错异常信息
             e.printStackTrace();
        }
        return null;
    }
    public static String md5(String source){
        if (source==null||source.length()==0){
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        try {
            String algorithm = "md5";
            MessageDigest md5 = MessageDigest.getInstance(algorithm);
            byte[] digest = md5.digest(source.getBytes());
            BigInteger bigInteger = new BigInteger(1, digest);
            String encode = bigInteger.toString(16).toUpperCase();
            return encode;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 如果是Ajax请求则返回true
     * @param request
     * @return
     */
    public static boolean judgeRequestType(HttpServletRequest request){
        String accept = request.getHeader("Accept");
        return (accept!=null&&accept.contains("application/json"));
    }

    /**
     *
     * @param endpoint  当前OSS的节点
     * @param accessKeyId   用户身份密匙
     * @param accessKeySecret   用户安全密匙
     * @param inputStream   文件输入流
     * @param bucketName    文件存入桶的名称
     * @param bucketDomain  通加文件夹的名称
     * @param originalName  文件的原始名称
     * @return
     */
    public static ResultEntity uploadFileToOSS(String endpoint,
                                               String accessKeyId,
                                               String accessKeySecret,
                                               InputStream inputStream,
                                               String bucketName,
                                               String bucketDomain,
                                               String originalName){
        OSS build = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String folderName = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String fileMainName = UUID.randomUUID().toString().replace("-", "");
        String extensionName = originalName.substring(originalName.lastIndexOf("."));
        String objectName=folderName+"/"+fileMainName+extensionName;
        try {
            PutObjectResult putObjectResult = build.putObject(bucketName, objectName, inputStream);
            ResponseMessage response = putObjectResult.getResponse();
            if (response==null){
                String ossFileAccessPath=bucketDomain+"/"+objectName;
                return ResultEntity.successWithData(ossFileAccessPath);
            }else {
                int statusCode = response.getStatusCode();
                String errorResponseAsString = response.getErrorResponseAsString();
                return ResultEntity.failed("当前相应状态码"+statusCode+"错误消息为："+errorResponseAsString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }finally {
            if (build!=null){
                build.shutdown();
            }
        }
    }

}
